<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - 宠物医院管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="${pageContext.request.contextPath}/css/style.css" rel="stylesheet">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <div class="col-md-2 p-0">
                <%@ include file="../common/admin-sidebar.jsp" %>
            </div>

            <!-- 主内容区域 -->
            <div class="col-md-10">
                <div class="main-content p-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">用户管理</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <div class="btn-group me-2">
                            <a href="${pageContext.request.contextPath}/user/add" class="btn btn-sm btn-outline-secondary">
                                <i class="fas fa-plus"></i> 添加用户
                            </a>
                            <button type="button" class="btn btn-sm btn-success" onclick="showImportModal()">
                                <i class="fas fa-upload"></i> 导入用户
                            </button>
                            <a href="${pageContext.request.contextPath}/user/downloadTemplate" class="btn btn-sm btn-info">
                                <i class="fas fa-download"></i> 下载模板
                            </a>
                        </div>
                    </div>
                </div>

                <!-- 消息提示 -->
                <c:if test="${not empty param.success}">
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        ${param.success}
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                </c:if>
                <c:if test="${not empty param.error}">
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        ${param.error}
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                </c:if>

                <!-- 搜索表单 -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="card-title mb-0">搜索条件</h5>
                    </div>
                    <div class="card-body">
                        <form method="get" action="${pageContext.request.contextPath}/user/list">
                            <div class="row">
                                <div class="col-md-3">
                                    <label for="username" class="form-label">用户名</label>
                                    <input type="text" class="form-control" id="username" name="username" 
                                           value="${username}" placeholder="输入用户名">
                                </div>
                                <div class="col-md-3">
                                    <label for="realName" class="form-label">真实姓名</label>
                                    <input type="text" class="form-control" id="realName" name="realName" 
                                           value="${realName}" placeholder="输入真实姓名">
                                </div>
                                <div class="col-md-3">
                                    <label for="userType" class="form-label">用户类型</label>
                                    <select class="form-select" id="userType" name="userType">
                                        <option value="">全部</option>
                                        <option value="admin" ${userType == 'admin' ? 'selected' : ''}>管理员</option>
                                        <option value="user" ${userType == 'user' ? 'selected' : ''}>普通用户</option>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label for="status" class="form-label">状态</label>
                                    <select class="form-select" id="status" name="status">
                                        <option value="">全部</option>
                                        <option value="active" ${status == 'active' ? 'selected' : ''}>正常</option>
                                        <option value="inactive" ${status == 'inactive' ? 'selected' : ''}>禁用</option>
                                    </select>
                                </div>
                            </div>
                            <div class="row mt-3">
                                <div class="col-12">
                                    <button type="submit" class="btn btn-primary me-2">
                                        <i class="fas fa-search"></i> 搜索
                                    </button>
                                    <a href="${pageContext.request.contextPath}/user/list" class="btn btn-secondary">
                                        <i class="fas fa-undo"></i> 重置
                                    </a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- 用户列表 -->
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="card-title mb-0">用户列表</h5>
                        <div>
                            <button type="button" class="btn btn-sm btn-danger" onclick="batchDelete()" disabled id="batchDeleteBtn">
                                <i class="fas fa-trash"></i> 批量删除
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <c:choose>
                            <c:when test="${not empty pageResult.data}">
                                <form id="batchForm">
                                    <div class="table-responsive">
                                        <table class="table table-striped table-hover">
                                            <thead>
                                                <tr>
                                                    <th>
                                                        <input type="checkbox" id="selectAll" onchange="toggleSelectAll()">
                                                    </th>
                                                    <th>用户ID</th>
                                                    <th>用户名</th>
                                                    <th>真实姓名</th>
                                                    <th>用户类型</th>
                                                    <th>手机号</th>
                                                    <th>邮箱</th>
                                                    <th>状态</th>
                                                    <th>
                                                        <a href="javascript:void(0)" onclick="sortBy('createTime')" class="text-decoration-none text-dark">
                                                            注册时间
                                                            <c:choose>
                                                                <c:when test="${sortField == 'createTime' && sortOrder == 'asc'}">
                                                                    <i class="fas fa-sort-up text-primary"></i>
                                                                </c:when>
                                                                <c:when test="${sortField == 'createTime' && sortOrder == 'desc'}">
                                                                    <i class="fas fa-sort-down text-primary"></i>
                                                                </c:when>
                                                                <c:otherwise>
                                                                    <i class="fas fa-sort text-muted"></i>
                                                                </c:otherwise>
                                                            </c:choose>
                                                        </a>
                                                    </th>
                                                    <th>操作</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <c:forEach var="user" items="${pageResult.data}">
                                                    <tr>
                                                        <td>
                                                            <input type="checkbox" name="userIds" value="${user.userId}" 
                                                                   onchange="updateBatchDeleteButton()">
                                                        </td>
                                                        <td>${user.userId}</td>
                                                        <td>${user.username}</td>
                                                        <td>${user.realName}</td>
                                                        <td>
                                                            <c:choose>
                                                                <c:when test="${user.userType == 'admin'}">
                                                                    <span class="badge bg-danger">管理员</span>
                                                                </c:when>
                                                                <c:otherwise>
                                                                    <span class="badge bg-primary">普通用户</span>
                                                                </c:otherwise>
                                                            </c:choose>
                                                        </td>
                                                        <td>${user.phone}</td>
                                                        <td>${user.email}</td>
                                                        <td>
                                                            <c:choose>
                                                                <c:when test="${user.status == 'active'}">
                                                                    <span class="badge bg-success">正常</span>
                                                                </c:when>
                                                                <c:otherwise>
                                                                    <span class="badge bg-secondary">禁用</span>
                                                                </c:otherwise>
                                                            </c:choose>
                                                        </td>
                                                        <td>
                                                            <fmt:formatDate value="${user.createTime}" pattern="yyyy-MM-dd"/>
                                                        </td>
                                                        <td>
                                                            <div class="btn-group btn-group-sm">
                                                                <a href="${pageContext.request.contextPath}/user/edit?id=${user.userId}" 
                                                                   class="btn btn-outline-primary" title="编辑">
                                                                    <i class="fas fa-edit"></i>
                                                                </a>
                                                                <c:if test="${user.userType != 'admin'}">
                                                                    <button type="button" class="btn btn-outline-danger"
                                                                            onclick="deleteUser(${user.userId})" title="删除">
                                                                        <i class="fas fa-trash"></i>
                                                                    </button>
                                                                </c:if>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                </c:forEach>
                                            </tbody>
                                        </table>
                                    </div>
                                </form>

                                <!-- 分页 -->
                                <c:if test="${pageResult.totalPages > 1}">
                                    <nav aria-label="用户分页">
                                        <ul class="pagination justify-content-center">
                                            <c:if test="${pageResult.currentPage > 1}">
                                                <li class="page-item">
                                                    <a class="page-link" href="?page=${pageResult.currentPage - 1}&size=${pageSize}">上一页</a>
                                                </li>
                                            </c:if>
                                            
                                            <c:forEach begin="1" end="${pageResult.totalPages}" var="i">
                                                <c:choose>
                                                    <c:when test="${i == pageResult.currentPage}">
                                                        <li class="page-item active">
                                                            <span class="page-link">${i}</span>
                                                        </li>
                                                    </c:when>
                                                    <c:otherwise>
                                                        <li class="page-item">
                                                            <a class="page-link" href="?page=${i}&size=${pageSize}">${i}</a>
                                                        </li>
                                                    </c:otherwise>
                                                </c:choose>
                                            </c:forEach>
                                            
                                            <c:if test="${pageResult.currentPage < pageResult.totalPages}">
                                                <li class="page-item">
                                                    <a class="page-link" href="?page=${pageResult.currentPage + 1}&size=${pageSize}">下一页</a>
                                                </li>
                                            </c:if>
                                        </ul>
                                    </nav>
                                </c:if>

                                <!-- 分页信息 -->
                                <div class="d-flex justify-content-between align-items-center mt-3">
                                    <div>
                                        共 ${pageResult.totalCount} 条记录
                                    </div>
                                    <div>
                                        <select class="form-select form-select-sm" onchange="changePageSize(this.value)" style="width: auto;">
                                            <option value="10" ${pageSize == 10 ? 'selected' : ''}>每页10条</option>
                                            <option value="20" ${pageSize == 20 ? 'selected' : ''}>每页20条</option>
                                            <option value="50" ${pageSize == 50 ? 'selected' : ''}>每页50条</option>
                                        </select>
                                    </div>
                                </div>
                            </c:when>
                            <c:otherwise>
                                <div class="text-center py-4">
                                    <i class="fas fa-users fa-3x text-muted mb-3"></i>
                                    <p class="text-muted">暂无用户数据</p>
                                    <a href="${pageContext.request.contextPath}/user/add" class="btn btn-primary">
                                        <i class="fas fa-plus"></i> 添加第一个用户
                                    </a>
                                </div>
                            </c:otherwise>
                        </c:choose>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 导入用户模态框 -->
    <div class="modal fade" id="importModal" tabindex="-1" aria-labelledby="importModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="importModalLabel">导入用户数据</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="importForm" enctype="multipart/form-data">
                    <div class="modal-body">
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            <strong>导入说明：</strong>
                            <ul class="mb-0 mt-2">
                                <li>请使用提供的Excel模板文件</li>
                                <li>用户名必须唯一，不能重复</li>
                                <li>密码将自动设置为"123456"，用户首次登录后请修改</li>
                                <li>支持的文件格式：.xlsx</li>
                                <li>最大文件大小：10MB</li>
                            </ul>
                        </div>

                        <div class="mb-3">
                            <label for="importFile" class="form-label">选择Excel文件 <span class="text-danger">*</span></label>
                            <input type="file" class="form-control" id="importFile" name="importFile"
                                   accept=".xlsx,.xls" required>
                            <div class="form-text">请选择要导入的Excel文件</div>
                        </div>

                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="skipDuplicates" name="skipDuplicates" value="true">
                            <label class="form-check-label" for="skipDuplicates">
                                跳过重复的用户名（不勾选则导入失败）
                            </label>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-upload me-2"></i>开始导入
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 全选/取消全选
        function toggleSelectAll() {
            const selectAll = document.getElementById('selectAll');
            const checkboxes = document.querySelectorAll('input[name="userIds"]');
            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAll.checked;
            });
            updateBatchDeleteButton();
        }

        // 更新批量删除按钮状态
        function updateBatchDeleteButton() {
            const checkboxes = document.querySelectorAll('input[name="userIds"]:checked');
            const batchDeleteBtn = document.getElementById('batchDeleteBtn');
            batchDeleteBtn.disabled = checkboxes.length === 0;
        }

        // 批量删除
        function batchDelete() {
            const checkboxes = document.querySelectorAll('input[name="userIds"]:checked');
            if (checkboxes.length === 0) {
                alert('请选择要删除的用户');
                return;
            }

            if (confirm('确定要删除选中的 ' + checkboxes.length + ' 个用户吗？此操作不可恢复！')) {
                const form = document.getElementById('batchForm');
                form.action = '${pageContext.request.contextPath}/user/batchDelete';
                form.method = 'post';
                form.submit();
            }
        }

        // 删除单个用户
        function deleteUser(userId) {
            if (confirm('确定要删除这个用户吗？此操作不可恢复！')) {
                window.location.href = '${pageContext.request.contextPath}/user/delete?id=' + userId;
            }
        }



        // 改变每页显示数量
        function changePageSize(size) {
            const url = new URL(window.location);
            url.searchParams.set('size', size);
            url.searchParams.set('page', '1');
            window.location.href = url.toString();
        }

        // 排序功能
        function sortBy(field) {
            const url = new URL(window.location);
            const currentSortField = url.searchParams.get('sortField');
            const currentSortOrder = url.searchParams.get('sortOrder');

            let newSortOrder = 'asc';
            if (currentSortField === field && currentSortOrder === 'asc') {
                newSortOrder = 'desc';
            }

            url.searchParams.set('sortField', field);
            url.searchParams.set('sortOrder', newSortOrder);
            url.searchParams.set('page', '1'); // 重置到第一页
            window.location.href = url.toString();
        }

        // 显示导入模态框
        function showImportModal() {
            const modal = new bootstrap.Modal(document.getElementById('importModal'));
            modal.show();
        }

        // 处理导入表单提交
        document.getElementById('importForm').addEventListener('submit', function(e) {
            e.preventDefault();

            const fileInput = document.getElementById('importFile');
            const file = fileInput.files[0];

            if (!file) {
                alert('请选择要导入的Excel文件');
                return;
            }

            // 检查文件类型
            const allowedTypes = ['.xlsx', '.xls'];
            const fileName = file.name.toLowerCase();
            const isValidType = allowedTypes.some(type => fileName.endsWith(type));

            if (!isValidType) {
                alert('请选择Excel文件（.xlsx或.xls格式）');
                return;
            }

            // 检查文件大小（10MB）
            if (file.size > 10 * 1024 * 1024) {
                alert('文件大小不能超过10MB');
                return;
            }

            // 创建FormData对象
            const formData = new FormData();
            formData.append('importFile', file);
            formData.append('skipDuplicates', document.getElementById('skipDuplicates').checked);

            // 显示加载状态
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>导入中...';
            submitBtn.disabled = true;

            // 发送请求
            fetch('${pageContext.request.contextPath}/user/import', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                console.log('Response status:', response.status);
                return response.json();
            })
            .then(data => {
                console.log('Response data:', data);
                if (data.success) {
                    alert('导入成功！共导入 ' + data.successCount + ' 个用户' +
                          (data.skipCount > 0 ? '，跳过 ' + data.skipCount + ' 个重复用户' : '') +
                          (data.errorCount > 0 ? '，失败 ' + data.errorCount + ' 个用户' : ''));
                    location.reload();
                } else {
                    alert('导入失败：' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('导入失败，请重试');
            })
            .finally(() => {
                // 恢复按钮状态
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            });
        });
    </script>
</body>
</html>
